{% extends base %}

{% block head %}
<link rel="stylesheet" type="text/css" href="/static/lib/webuploader/webuploader.css">
<script type="text/javascript" src="/static/lib/webuploader/webuploader.nolog.min.js"></script>

<style type="text/css">
    .chat-box {
        /*background-color: #CCFF99;*/
    }

    .chat-avatar {
        color: #2092d9;
    }

    .finished {
        color: #fff;
        background-color: green;
    }
    .in-progress {
        background-color: #f90;
        color: white;
    }

    .suspended {
        background-color: #aaa;
        color: white;
    }

    .chat-msg {
        margin-top: 0.1rem;
        float: left;
    }

    .chat-msg-content {
        border-width: 5px;
        border-radius: 5px;
        word-wrap: break-word;
        word-break: break-all;
        /*background-color: #99CCFF;*/
        padding: 5px 0px;
    }

    .chat-msg-img {
        width: 180px;
    }
    .chat-msg-option {
        /*text-align: center;*/
        color: #888;
        margin: 0;
        font-size: 10px;
    }
    .chat-msg-time {
        display: inline-block;
        float: right;
        padding: 2px;
    }

    .input-box {
        /*position: relative;*/
        /*left: 0;*/
        /*right: 0;*/
        /*width: calc(100% - 5rem);*/
        width: 100%;
        outline: none;
    }

    .send-button {
        float: left;
        width: 4rem;
        margin-top: 0.5rem;
        margin-right: 0.5rem;
    }

    .right {
        float: right;
    }

</style>
{% end %}

{% block body %}
{% init key = "" %}
<script src="/static/lib/vue/vue-2.2.6.min.js"></script>
{% include common/mod_search.html %}
<div id="app" class="col-md-12">
    {# include common/mod_notice.html #}

    {% include "message/header.html" %}

    <div class="message-input col-md-12 card">
        <textarea class="col-md-12 input-box" v-model="input" v-bind:rows="input.count('\n')+3" placeholder="快速记录灵感、备忘、任务等"></textarea>
        <input type="file" id="filePicker" class="hide" multiple/>
        <input type="button" id="filePickerBtn" class="send-button btn btn-default" value="添加附件"/>
        <input type="button" name="" class="send-button btn" value="创建" @click="sendMessage()">
        <div id="uploadProgress" style="float: right;" ></div>
    </div>

    <div class="chat-box col-md-12">
        <div class="message-row" v-if="messageList.length == 0">
            空空如也~
        </div>
        <div class="message-row" v-for="message in messageList">
            <div class="chat-avatar col-md-12">
                <!-- {{! message.ctime }} -->
                <!-- <span class="tag-span" v-if="message.status==100">已完成</span> -->
            </div>
            <div class="chat-msg col-md-12">
                <template v-if="message.editable">
                    <textarea class="input-box col-md-12" v-bind:rows="message.content.count('\n')+3" v-model="message.content"></textarea>
                    <input type="button" value="更新" v-on:click="updateMessage(message)">
                    <input type="button" value="删除" class="btn-danger" v-if="message.user==current_user" v-bind:msg-id="message.id" v-bind:msg-content="message.content" href="javascript:void(0)" @click="deleteMessage($event)">
                    <input type="button" value="取消" v-on:click="message.editable = false" class="btn-cancel">
                </template>
                <div v-else>
                    <div v-if="message.link">
                        <a v-bind:href="message.link">{{! message.link }}</a>
                    </div>
                    <div v-if="message.imgSrc">
                        <a v-bind:href="message.imgSrc">
                            <img v-bind:src="message.imgSrc" class="chat-msg-img x-photo"/>
                        </a>
                    </div>
                    <!-- 解析出的html -->
                    <div v-if="message.html" class="chat-msg-content" v-html="message.html">
                    </div>
                    <!-- 操作 -->
                    <div class="col-md-12">
                        <p class="chat-msg-option">
                            <span class="chat-msg-time">{{! message.ctime }}</span>
                            <span class="inline-tag in-progress" v-if="message.status==0">待办</span>
                            <a class="smallText" v-if="message.status!=0" v-bind:msg-id="message.id" href="javascript:void(0)" @click="openMessage($event)">待办</a>

                            <span class="inline-tag suspended" v-if="message.status==50">挂起</span>
                            <a class="smallText" v-if="message.status!=50" v-bind:msg-id="message.id" href="javascript:void(0)" @click="updateStatus($event, 50)">挂起</a>
                            
                            <span class="inline-tag finished" v-if="message.status==100">完成</span>
                            <a class="smallText" v-if="message.status!=100" v-bind:msg-id="message.id" href="javascript:void(0)" @click="finishMessage($event)">完成</a>
                            
                            <a class="smallText" v-on:click="(message.editable = true) && console.log(message, messageList)" href="javascript:void(0)">编辑</a>
                           <!-- <a class="smallText" v-if="message.user==current_user" v-bind:msg-id="message.id" v-bind:msg-content="message.content" href="javascript:void(0)" style="color: red;" @click="deleteMessage($event)">删除</a>  -->
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-12 grid-card">
        <a class="x-page-link" href="#">共{{!page_max}}页/{{!amount}}条</a> 
        <a v-if="page > 1" class="x-page-link" v-bind:href="page_prev_url">上一页</a>
        <a class="x-page-link x-page-active" href="#">{{!page}}</a>
        <a v-if="page < page_max" class="x-page-link" v-bind:href="page_next_url">下一页</a>
    </div>
</div>

<script type="text/javascript">
    // 获取地址
    if (false && navigator.geolocation && window.xuser != "") {
        navigator.geolocation.getCurrentPosition(function (pos) {
            console.log(pos);
            if (pos && pos.coords) {
                // JSON.stringify 无效
                var latitude = pos.coords.latitude;
                var longitude = pos.coords.longitude;
                var accuracy = pos.coords.accuracy;

                var coords = {
                    latitude: latitude, 
                    longitude:longitude, 
                    accuracy: accuracy,
                    heading: pos.coords.heading,
                    speed: pos.coords.speed,
                    altitude: pos.coords.altitude,
                    altitudeAccuracy: pos.coords.altitudeAccuracy
                };
            }
        });
    }

    function newMessage(content, user, status) {
        return {"content": content, user:user, status:status}
    }

    function wrapMessage(message) {
        message.editable = false;
        return message;
        var content = message.content;
        var reg = /file:\/\/([\S]+)\n*(.*)/gi;
        var parts = reg.exec(content);
        if (parts) {
            var path = parts[1];
            var text = parts[2];
            var lowerPath = path.toLowerCase();
            if (lowerPath.endsWith(".jpg") || lowerPath.endsWith(".jpeg") || 
                    lowerPath.endsWith(".png") || lowerPath.endsWith(".gif")) {
                message.imgSrc = path;
            } else {
                message.link = path;
            }
            message.html = text;
        } else {
            var html = content.replace(/(https*:\/\/[^ \t\r\n]+)/gi, '<a href="$1">$1</a>');
            html = html.replace(/\n/gi, "<br>");
            message.html = html;
        }
        return message;
    }

    var app = new Vue({
        el: "#app",
        data: {
            title: "消息",
            message: "Hello, Vue!",
            messageList: [newMessage("Welcome to chatroom")],
            person: {
                name:"Jhon",
                age: 20,
            },
            bindmessage: "页面加载于 " + new Date(),
            seen: false,
            rawHtml: "{{!message}}",
            url: "https://www.baidu.com",
            input: "",
            page_max: 2,
            page: 1,
            page_url: "/message?pagesize=20&page=",
            page_next_url:"#",
            page_prev_url:"#",
            current_user:"",
            status: "",
            amount: 0
        },
        methods: {

            init: function () {
                this.status = getUrlParams().status;
                var tag = getUrlParam("tag");
                this.page_url = "/message?status=%s&pagesize=20&key={{key}}&tag=%s&page=".format(this.status, tag);

                if (tag == "file") {
                    $("#tabFile").addClass("tab-link-active");
                }
            },

            refreshMessage: function () {
                var self = this;
                var page = getUrlParams().page || 1;
                var tag  = getUrlParam("tag");
                app.page = page;
                app.page_next_url = app.page_url + (parseInt(page)+1);
                app.page_prev_url = app.page_url + (page-1);
                $.get("/message/list", 
                    {pagesize:20,page:page,status:self.status,key:"{{key}}",tag:tag}, 
                    function (respText) {
                        var data = respText;
                        app.page_max = data.page_max;
                        app.current_user = data.current_user;
                        if (data.code == "success") {
                            var messageList = [];
                            data.data.forEach(function (item, index) {
                                // console.log(item, index);
                                messageList.push(wrapMessage(item));
                            })
                            messageList.reverse();
                            self.messageList = messageList;
                            self.amount = data.amount;
                        }
                })
            },

            sendMessage: function () {
                if (this.input == "") {
                    return;
                }
                var self = this;
                $.post("/message/add", 
                    {
                        content:self.input, 
                        status: getUrlParam("status")
                    },
                    function (respText) {
                        var data = respText;
                        if (data.code == "success") {
                            var msg = wrapMessage(data.data);
                            self.messageList.push(msg);
                            self.input = "";
                        } else {
                            alert(data.message);
                        }
                        app.refreshMessage();
                }).fail(function (data) {

                })
            },

            deleteMessage: function (event) {
                var el = event.currentTarget;
                var self = this;
                var id = $(el).attr("msg-id");
                var content = $(el).attr("msg-content");
                var check = confirm("确认删除 '%s' ?".format(content));
                if (check) {                
                    $.post("/message/remove", {id: id}, function (resp) {
                        if (resp.code == "success") {
                            app.refreshMessage();
                        } else {
                            alert(data.message);
                        }
                    });
                }
            },

            finishMessage: function (event) {
                var el = event.currentTarget;
                var self = this;
                var id = $(el).attr("msg-id");
                $.post("/message/finish", {id: id}, function (resp) {
                    if (resp.code == "success") {
                        app.refreshMessage();
                    } else {
                        alert(data.message);
                    }
                });
            },

            openMessage: function (event) {
                var el = event.currentTarget;
                var self = this;
                var id = $(el).attr("msg-id");
                $.post("/message/open", {id: id}, function (resp) {
                    if (resp.code == "success") {
                        app.refreshMessage();
                    } else {
                        alert(data.message);
                    }
                });
            },

            updateMessage: function (message) {
                $.post("/message/update", message, function (resp) {
                    console.log(resp);
                    app.refreshMessage();
                })
            },

            updateStatus: function (event, status) {
                var id = $(event.currentTarget).attr("msg-id");
                var message = {id: id, status: status};
                $.post("/message/status", message, function (resp) {
                    console.log(resp);
                    app.refreshMessage();
                });
            }
        }
    });

    app.init();
    app.refreshMessage();

    // 文件上传
    var BASE_URL = "/static/lib/webuploader"
    // 初始化Web Uploader
    var uploader = xnote.createUploader();

    // 当有文件添加进来的时候
    uploader.on( 'fileQueued', function( file ) {
        var $li = $(
                '<div id="' + file.id + '" class="file-item thumbnail">' +
                    '<img>' +
                    '<div class="info">' + file.name +
                    '<span class="finished-tag" id="' + file.id + '-result"></span>' + 
                     '</div>' +
                '</div>'
                ),
            $img = $li.find('img');

        $list = $("#fileList");
        // $list为容器jQuery实例
        $list.append( $li );

        // 创建缩略图
        // 如果为非图片文件，可以不用调用此方法。
        // thumbnailWidth x thumbnailHeight 为 100 x 100
        var thumbnailWidth = 100;
        var thumbnailHeight = 100;
        uploader.makeThumb( file, function( error, src ) {
            if ( error ) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }

            $img.attr( 'src', src );
        }, thumbnailWidth, thumbnailHeight );
    });


    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#uploadProgress' ),
        $percent = $li.find('.progress span');

        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<div class="progress"><span></span></div>')
                    .appendTo( $li )
                    .find('span');
        }

        $percent.css( 'width', percentage * 100 + '%' );
        $percent.text( (percentage * 100).toFixed(2) + '%');
    });

    uploader.on( 'uploadBeforeSend', function (object, data, headers) {
        $( '#uploadProgress' ).find('.progress').remove();
        data.dirname = "auto";
    })

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.on( 'uploadSuccess', function( file, resp) {
        $( '#uploadProgress' ).find('.progress').remove();
        var $li = $( '#uploadProgress' );
        $('<div class="progress"><span>上传完成</span></div>')
                    .appendTo( $li )
                    .find('span');
        file.webpath = resp.webpath;
    });

    // 文件上传失败，显示上传出错。
    uploader.on( 'uploadError', function( file ) {
        var $li = $( '#'+file.id ),
            $error = $li.find('div.error');

        // 避免重复创建
        if ( !$error.length ) {
            $error = $('<div class="error"></div>').appendTo( $li );
        }

        $error.text('上传失败');
    });

    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.on( 'uploadComplete', function( file ) {
        var webpath = file.webpath;
        var content = 'file://$name'.replace(/\$name/g, file.webpath);
        app.input += content + "\n";
    });

    $("#filePickerBtn").on("click", function (event) {
        console.log("select file button click");
        $("#filePicker").click();
    })

    $("#filePicker").on("change", function (event) {
        console.log(event);
        var fileList = event.target.files; //获取文件对象 
        console.log(fileList);
        if (fileList && fileList.length > 0) {
            uploader.addFile(fileList);
        }
    });

</script>

{% end %}

{% block aside %}
    {% include message/message_aside.html %}
{% end %}